# main.py（升级版）
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ValidationError
from typing import Optional

app = FastAPI()

fake_db = []

# Pydantic 模型
class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float] = None

@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.dict()
    item_dict["id"] = len(fake_db) + 1
    fake_db.append(item_dict)
    return item_dict

# 错误处理中间件
@app.exception_handler(ValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        status_code=400,
        content={"detail": exc.errors()}
    )
    
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)     
    print("Server running on http://0.0.0.0:8000")
    print("Press Ctrl+C to stop the server")